import React, { useEffect, useState } from "react";
import { Button, Container, ListGroup } from "react-bootstrap";
import AddOrEditChatGroup from './edit';
import { useNavigate, useNavigation } from "react-router-dom";
import ChatService from "../../../services/chatservice";
import { UserHelper } from "../../../helper";
import { PopupDialog } from "../../../components/common";

interface ChatGroupProps{

}

// a private group or group owned by a channel.
const ChatGroup:React.FC<ChatGroupProps> = (props:ChatGroupProps)=> {
    
    const navigate = useNavigate();
    const [groupList,setGroupList] = useState([]);

    useEffect(()=>{
        ChatService.getGroups({userid:UserHelper.getCachedUserInfo().userid||""}).then((list)=>{
            setGroupList(list);
        }).catch((err)=>{
            PopupDialog.showBsError(err);
        })
    },[])


    const addGroup = ()=> {
        navigate("/chat/addgroup")
    }

    const onClickGroup = (group:any)=> {
        navigate("/chat/dialog",{state:{
            group:group
        }});
    }

    return (<Container fluid className="d-flex flex-column m-0 px-1 py-1">
                <Button className="align-self-end"
                        size="sm" 
                        variant="link" 
                        onClick={addGroup}
                        >Add Group</Button>
                <ListGroup>
                    {groupList.map((group:any,index)=>{
                        // {"groupId":"f5cbf837-a302-4e98-846e-0766b306aa3c","ownerId":
                        // "641dd097-a40f-4b52-ab59-1fef62bf9f81","channelId":"undefined",
                        // "groupName":"test","groupDesc":"test","groupTag":null,
                        // "gpStatus":0,"groupMemberLimit":null}
                        return (<ListGroup.Item key={group.groupId}>
                            <Container className="d-flex flex-row"
                                style={{height:60}}  
                                onClick={(e)=>{
                                    e.preventDefault();
                                    onClickGroup(group);
                                }}>
                                <Container className="d-flex flex-column">
                                    <p>{group.groupName}</p>
                                </Container>
                                <Container>
                                <p className="text-end">{group.groupTag||"General"}</p>
                                </Container>
                            </Container>
                        </ListGroup.Item>)
                    })}
                </ListGroup>
            </Container>)
}

export default ChatGroup;
export {
    AddOrEditChatGroup
}